﻿using System;
using MvcContrib.FluentHtml;
using MvcContrib.FluentHtml.Elements;
using MvcContrib.FluentHtml.Expressions;

namespace MvcMall.Framework.Extensions
{
   public static class ViewModelContainerExtensions
    {
       /// <summary>
        /// 获取ViewModel的值
       /// </summary>
       /// <typeparam name="TModel"></typeparam>
       /// <typeparam name="TValue"></typeparam>
       /// <param name="view"></param>
       /// <param name="expression"></param>
       /// <returns></returns>
        public static TValue ValueFor<TModel, TValue>(this IViewModelContainer<TModel> view, System.Linq.Expressions.Expression<Func<TModel, TValue>> expression)
            where TModel : class where TValue : class
       {
            var name = expression.GetNameFor();
            var value = expression.GetValueFrom(view.ViewModel);
            if (null == value)
            {
                if (view.ViewData.ModelState.Keys.Contains(name) && null != view.ViewData.ModelState[name].Value) 
                    return value = view.ViewData.ModelState[name].Value.AttemptedValue as TValue; 
            }
            return value;
        }
        /// <summary>
        /// 日期选择TextBox
        /// </summary>
        /// <typeparam name="TModel"></typeparam> 
        /// <param name="view"></param>
        /// <param name="expression"></param>
        /// <returns></returns>
        public static TextBox DateTextBox<TModel >(this IViewModelContainer<TModel> view, System.Linq.Expressions.Expression<Func<TModel ,object>> expression)
            where TModel : class 
        {
            return view.TextBox(expression).Class("datepicker").Attr("readonly", "readonly");
        }   
       /// <summary>
        /// 日期时间选择TextBox
        /// </summary>
        /// <typeparam name="TModel"></typeparam> 
        /// <param name="view"></param>
        /// <param name="expression"></param>
        /// <returns></returns>
        public static TextBox DateTimeTextBox<TModel >(this IViewModelContainer<TModel> view, System.Linq.Expressions.Expression<Func<TModel ,object>> expression)
            where TModel : class 
        {
            return view.TextBox(expression).Class("timepicker").Attr("readonly", "readonly");
        }
    }
}
